package servlet;

import User.User;
import database.MyDB;

import java.io.DataOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name="LoginServlet")
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        System.out.println("LoginServlet: 用户登录请求");
        
        // 获取请求参数
        String name = request.getParameter("name");
        String password = request.getParameter("pwd");
        
        // 参数验证
        if (name == null || password == null || name.isEmpty() || password.isEmpty()) {
            sendResponse(response, "F");
            return;
        }
        
        // 创建用户对象并设置参数
        User user = new User();
        user.setName(name);
        user.setPwd(password);
        
        // 验证用户登录
        MyDB myDB = new MyDB();
        String result = "F";
        
        if (myDB.validateUser(user)) {
            result = "T";
            // 创建会话，存储用户信息
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            System.out.println("LoginServlet: 用户登录成功 - " + user.getName());
        } else {
            System.out.println("LoginServlet: 用户登录失败 - " + name);
        }
        
        // 发送响应
        sendResponse(response, result);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 支持POST请求，调用doGet方法
        doGet(request, response);
    }
    
    // 发送响应辅助方法
    private void sendResponse(HttpServletResponse response, String result) throws IOException {
        response.setContentType("text/plain");
        // 使用单个PrintWriter实例
        java.io.PrintWriter writer = null;
        IOException caughtException = null;
        try {
            writer = response.getWriter();
            writer.write(result);
        } catch (IOException e) {
            caughtException = e;
            throw e;
        } finally {
            try {
                if (writer != null) {
                    writer.flush();
                    writer.close();
                }
            } catch (Exception e) {
                // 如果关闭资源时出错且之前没有异常，则打印堆栈
                if (caughtException == null) {
                    e.printStackTrace();
                }
            }
        }
    }
}